import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import TableRender, { type TableRenderColumnTypes } from '@/render/TableRender'
import type { VxeGridDefines, VxeGridProps } from 'vxe-table'
import Dialog from '@/components/dialog/Index'
import type { ProductDto } from '@/api/deal/types'
import type { AnyObject } from '@/types'
import type { PageDto } from '@/api/types'
import type { FormModalDto } from '@/components/modal/Modal'
import renderModal, { getModelValue } from '@/components/modal/Modal'
import { getSaleList } from '@/api/sale'
import { handleAllocate } from '@/api/deal'
import dayjs from 'dayjs'
import { Button, message } from 'ant-design-vue'

@Component
export class DialogAllocateClient extends TableRender {
    @Prop() show!: boolean
    @Prop() productList!: ProductDto[]
    @Prop() saasUserId!: number
 
    noTablePadding = true
    showDialog = false

    selected = [] as ProductDto[]

    @Emit('update:show')
    updateShow(show: boolean) {
        return show
    }

    @Emit('refresh')
    handleRefresh() {}

    @Watch('show', { immediate: true })
    handleWatchShow() {
        this.showDialog = this.show
        this.show && this.reloadPage(1)
    }

    @Watch('showDialog')
    handleWatchShowDialog() {
        this.updateShow(this.showDialog)
    }

    tableColumnConfigOld = () => [
        { type: 'checkbox', width: 50, fixed: 'left' },
        {
            field: 'companyName',
            title: '客户资源名称',
            width: 200
        },
        {
            field: 'productTypeName',
            title: '产品'
        }
    ] as TableRenderColumnTypes<ProductDto>

    basicFormConfig = this.initFormConfig() as FormModalDto
    initFormConfig() {
        return {
            title: '选择分配销售',
            width: '400px',
            theme: 'light',
            show: false,
            spanAlign: 'left',
            items: {
                saleId: {
                    name: '销售名称',
                    element: 'select',
                    required: true,
                    callback: {
                        method: async () => {
                            const res = await getSaleList()
                            return res.filter(i => i.userId !== this.saasUserId).map(i=> {
                                return {
                                    label: i.saleName,
                                    value: i.saleId
                                }
                            })
                        }
                    }
                },
            },
            complete: async () => {
                const data = getModelValue(this.basicFormConfig)
                await handleAllocate({
                    ...data,
                    saleOldId: this.saasUserId,
                    companyIds: this.selected.map(i => i.companyId),
                    serviceStartTime: dayjs().startOf('month').format('YYYY-MM-DD'),
                })
                message.success('分配成功')
                this.handleRefresh()
                this.basicFormConfig.show = false
                this.showDialog = false
            },
            cancel: () => {
                this.basicFormConfig.show = false
            },
            init: () => {
            }
        } as FormModalDto
    }

    onShowDialog() {
        if (this.selected.length === 0) {
            message.warning('请选择要分配的客户资源')
            return
        }
        this.basicFormConfig.show = true
    }

    onCheckboxChange(row: VxeGridDefines.CheckboxChangeEventParams) {
        this.selected = this.ref.getCheckboxRecords() as ProductDto[]
    }

    onCheckboxAll(row: VxeGridDefines.CheckboxChangeEventParams) {
        this.selected = this.ref.getCheckboxRecords() as ProductDto[]
    }

    onLoadData(page: number, size: number, filters: AnyObject) {
        return new Promise<PageDto<ProductDto>>((resolve) => {
            resolve({
                list: this.productList,
                total: this.productList.length
            } as PageDto<ProductDto>)
        })
    }

    renderRightBtns() {
        return (
            <div class="flex w-full justify-between mb-16px">
                <Button size="small" onClick={this.onShowDialog}>
                    分配给其他成员
                </Button>
                <div>
                    共<span class="text-blue-default">{this.productList?.length ?? 0}位</span>客户
                </div>
            </div>
        )
    }

    render() {
        return (<>
            <Dialog
                v-model={this.showDialog}
                title="客户资源分配"
                v-slots={{
                    default: () => {
                        return (
                            <div>
                                {this.renderRightBtns()}
                                {super.renderTable()}
                                <div class="mt-16px">已选中{this.selected?.length}位客户</div>
                            </div>
                        )
                    }
                }}
            ></Dialog>
            {renderModal(this.basicFormConfig)}
        </>
        )
    }
}

export default toNative<{ productList: ProductDto[], saasUserId: number }, {refresh: () => void}>(DialogAllocateClient)
